import sounddevice as sd
import numpy as np
from queue import Queue

class AudioCapturer:
    """系统音频捕获类"""
    
    def __init__(self, sample_rate, channels, device, chunk_size):
        """
        初始化音频捕获设备
        :param sample_rate: 采样率
        :param channels: 声道数
        :param device: 输入设备
        :param chunk_size: 每次读取的音频块大小
        """
        self.sample_rate = sample_rate
        self.channels = channels
        self.device = device
        self.chunk_size = chunk_size
        self.audio_queue = Queue()
        self.stream = None

    def _callback(self, indata, frames, time, status):
        """音频回调函数，将音频数据放入队列"""
        if status:
            print(f"音频输入错误: {status}")
        self.audio_queue.put(indata.copy())

    def start_capture(self):
        """开始捕获音频"""
        self.stream = sd.InputStream(
            samplerate=self.sample_rate,
            channels=self.channels,
            device=self.device,
            callback=self._callback,
            blocksize=self.chunk_size
        )
        self.stream.start()

    def stop_capture(self):
        """停止捕获音频"""
        if self.stream:
            self.stream.stop()
            self.stream.close()

    def get_audio_data(self):
        """从队列获取音频数据"""
        if not self.audio_queue.empty():
            return self.audio_queue.get()
        return None 